/*******************************************************************************
 * Copyright (c) 2010 Mikhail Garber.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License (LGPL)
 * which accompanies this distribution
 * 
 * Contributors:
 *     Mikhail Garber - initial API and implementation
 ******************************************************************************/
package plumber.component;

import java.lang.reflect.Method;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import plumber.context.FlowContext;

/**
 * abstract parent of various Component Managers
 * @author mgarber
 *
 */
public abstract class AbstractComponentManager implements ComponentManager {

	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	protected Method findMethod(String methodName, Class<?> clazz) {
		for(Method m : clazz.getDeclaredMethods()) {
			if(m.getName().equals(methodName)) {
				return m;
			}
		}
		return null;
	}

	
	/**
	 * find component given its name and method name to be executed
	 */
	@Override
	public abstract Object find(String componentName, String methodName);


	/**
	 * find and execute component given its name, method name and item context
	 */
	@Override
	public Object execute(String componentName, String methodName,
			FlowContext context) {
			Object component = find(componentName, methodName);
			Method method = findMethod(methodName, component.getClass());
			logger.info(String.format("exec method:%s on object:%s", method.getName(), component.getClass()));
			try {
				Object result = method.invoke(component, new Object[] {context} );
				return result;
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		
	}

}
